package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdLoginVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: AdUserServiceImpl
 * Description:
 * date: 2023/8/21 0021 15:59
 *
 * @author zHan
 */
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 管理员登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        // 校验参数
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 根据用户名查询数据库
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        // 判断用户是否存在
        // 不存在，返回错误
        if (adUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 密码加盐后md5加密
        String password = dto.getPassword() + adUser.getSalt();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 加盐后的密码与数据库的密码对比
        if (!password.equals(adUser.getPassword())) {
            // 不正确，返回错误结果
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 正确，封装vo对象
        AdLoginVo adLoginVo = new AdLoginVo();
        BeanUtils.copyProperties(adUser,adLoginVo);
        // 封装map集合，包含token，user
        Map<String,Object> map=new HashMap<>();
        map.put("token", AppJwtUtil.getToken(Long.valueOf(adUser.getId())));
        map.put("user",adLoginVo);
        // 返回结果
        return ResponseResult.okResult(map);
    }
}
